import './user.scss'
import { useEffect, useState } from 'react'
import { Form, Input, message } from 'antd'
import { Tooltip, Table, Tag, Pagination, Button, DatePicker } from 'antd'
import { EditOutlined } from '@ant-design/icons'
import { reqAdminGetAllUser, reqAdminUpdateUser } from '@/api/admin'
import dayjs from 'dayjs'

function User() {
  const [edit, setEdit] = useState(false)
  const [userInfo, setUserInfo] = useState<any>([])
  const [pageSize, setPageSize] = useState(5)
  const [pageNo, setPageNo] = useState(1)
  const [total, setTotal] = useState(0)
  const [formData, setFormData] = useState<any>({})
  const [history, setHistory] = useState<any>({})
  const [form] = Form.useForm()

  useEffect(() => {
    if (edit) {
      form.setFieldsValue({
        ...formData,
        birthday: formData.birthday ? dayjs(formData.birthday) : null,
      })
    }
  }, [edit, formData, form])

  useEffect(() => {
    getAdminGetAllUser()
  }, [pageNo, pageSize])

  // 获取全部用户信息
  const getAdminGetAllUser = async () => {
    const res: any = await reqAdminGetAllUser({ pageNO: pageNo, pageSize })
    if (res.code === 200) {
      console.log(res.data)
      // 创建一个新数组，其中每个对象都有一个额外的 key 属性
      const newRecords = res.data.records.map((item: any) => ({
        ...item,
        key: item.id,
      }))
      setUserInfo(newRecords)
      setTotal(res.data.total)
    }
  }

  // 修改用户信息
  const updateUser = async () => {
    const res: any = await reqAdminUpdateUser(formData)
    if (res.code === 200) {
      message.success('修改成功')
      getAdminGetAllUser()
    }
  }

  const columns: any = [
    {
      title: '学生ID',
      width: 100,
      align: 'center',
      ellipsis: true,
      dataIndex: 'id',
    },
    {
      title: '姓名',
      align: 'center',
      ellipsis: true,
      dataIndex: 'username',
    },
    {
      title: '邮箱',
      align: 'center',
      ellipsis: true,
      dataIndex: 'email',
    },
    {
      title: '电话',
      align: 'center',
      ellipsis: true,
      dataIndex: 'phone',
      render: (text: any) => text || '未填写',
    },
    {
      title: '生日',
      align: 'center',
      ellipsis: true,
      dataIndex: 'birthday',
      render: (text: any) => (text ? dayjs(text).format('YYYY年MM月DD日') : '未填写'),
    },
    {
      title: '选课',
      align: 'center',
      ellipsis: true,
      key: 'school',
      dataIndex: 'school',
      render: (_: any, { school }: any) => (
        <>
          {school?.map((tag: any, index: number) => (
            <Tag color="success" key={index}>
              {tag.schoolName.toUpperCase()}
            </Tag>
          )) || '无'}
        </>
      ),
    },
    {
      title: '修改',
      key: 'action',
      width: 150,
      align: 'center',
      render: (data: any) => (
        <Tooltip title="修改信息">
          <Button
            ghost
            type="primary"
            shape="circle"
            onClick={() => {
              setEdit(true)
              setFormData(data)
              setHistory(data)
            }}
            icon={<EditOutlined />}
          ></Button>
        </Tooltip>
      ),
    },
  ]

  const handleChange = (page: number, pageSize: number) => {
    setPageNo(page)
    setPageSize(pageSize)
  }

  // 表单提交
  const onFinish = async () => {
    await form.validateFields()
    updateUser()
    setEdit(false)
  }

  // 点击重置按钮的回调
  const handleReset = () => {
    setFormData(history)
  }

  return (
    <div className="User">
      {!edit ? (
        <>
          <Table columns={columns} dataSource={userInfo} pagination={false} />
          <Pagination
            style={{ marginTop: '20px' }}
            pageSizeOptions={['3', '5', '7', '9']}
            showSizeChanger
            defaultPageSize={pageSize}
            onChange={handleChange}
            total={total}
            align="end"
          />
        </>
      ) : (
        <div className="form">
          <div className="form-content">
            <Form
              form={form}
              name="basic"
              size="large"
              layout="vertical"
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 24 }}
              style={{ maxWidth: 600 }}
              initialValues={{ remember: true }}
              autoComplete="off"
            >
              <Form.Item label="邮箱" name="email">
                <Input autoComplete="off" disabled />
              </Form.Item>
              <Form.Item
                label="姓名"
                name="username"
                rules={[{ required: true, message: '姓名不能为空！' }]}
                validateTrigger="onBlur"
              >
                <Input
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, username: e.target.value })}
                  autoComplete="off"
                />
              </Form.Item>
              <Form.Item
                label="电话"
                name="phone"
                rules={[{ required: true, message: '电话不能为空！' }]}
                validateTrigger="onBlur"
              >
                <Input
                  value={formData.phone}
                  onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                  autoComplete="off"
                />
              </Form.Item>
              <Form.Item
                label="生日"
                name="birthday"
                rules={[{ required: true, message: '生日不能为空！' }]}
                validateTrigger="onBlur"
              >
                <DatePicker
                  style={{ width: '100%' }}
                  value={formData.birthday}
                  onChange={(date) => setFormData({ ...formData, birthday: date })}
                />
              </Form.Item>
              <Form.Item label="课程">
                {formData.school?.map((data: any, index: number) => (
                  <Tag
                    color="success"
                    key={index}
                    style={{ padding: '8px 20px', marginBottom: '10px' }}
                  >
                    {data.schoolName}
                  </Tag>
                )) || ''}
              </Form.Item>
              <Form.Item>
                <Button onClick={handleReset}>重置</Button>
                <Button
                  style={{ margin: '0 20px' }}
                  onClick={() => {
                    form.resetFields()
                    setEdit(false)
                  }}
                >
                  退出
                </Button>
                <Button type="primary" onClick={onFinish}>
                  确定
                </Button>
              </Form.Item>
            </Form>
          </div>
        </div>
      )}
    </div>
  )
}

export default User
